package dao

import (
	"context"
	"sale-admin/internal/dal"
	"sale-admin/internal/models"
	"time"

	"192.168.1.75/go-pkg/helper"
	"github.com/golang-module/carbon/v2"
	"gorm.io/datatypes"
)

type RobotReportLog struct{}

func (RobotReportLog) Create(ctx context.Context, q *dal.Query, URL string, Type int, robotName, objectName string,
	webHookName int, webHookUrl, merchantID, object string, startTime, endTime time.Time) (err error) {
	m := q.MaRobotReportLog
	tx := m.WithContext(ctx)
	var d models.MaRobotReportLog
	d.ID, _ = helper.UUID{}.String()
	d.Url = URL
	d.Type = Type
	d.RobotName = robotName
	d.ObjectName = objectName
	d.WebHookName = webHookName
	d.WebHookAddress = webHookUrl
	d.MerchantID = merchantID
	d.Object = object
	d.StartTime = datatypes.Date(startTime)
	d.EndTime = datatypes.Date(endTime)
	d.AddTime = time.Now()
	d.CreatedAt = time.Now().Unix()
	err = tx.Create(&d)
	return
}

func (RobotReportLog) EmptyStockList(ctx context.Context, query *dal.Query, merchantID string, stockType int,
	startTime, endTime string, page, limit int) (res []*models.MaRobotReportLog, count int64, err error,
) {
	m := query.MaRobotReportLog
	tx := m.WithContext(ctx).
		Where(m.Object.Eq(merchantID))
	if stockType == 1 {
		tx = tx.Where(m.Type.Eq(4)) // 单日空货
	} else if stockType == 2 {
		tx = tx.Where(m.Type.Eq(5)) // 连续空货
	} else {
		tx = tx.Where(m.Type.In([]int{4, 5}...)) // 4单日空货5连续空货
	}
	if startTime != "" && endTime != "" {
		start := carbon.Parse(startTime).StartOfDay().ToStdTime()
		end := carbon.Parse(endTime).EndOfDay().ToStdTime()
		tx = tx.Where(m.AddTime.Between(start, end))
	}
	res, count, err = tx.Order(m.AddTime.Desc()).FindByPage(Offset(page, limit))
	return
}

func (RobotReportLog) List(ctx context.Context, query *dal.Query, merchantID string, Type int,
	startTime, endTime string, page, limit int) (res []*models.MaRobotReportLog, count int64, err error,
) {
	m := query.MaRobotReportLog
	tx := m.WithContext(ctx)
	if Type != 0 {
		tx = tx.Where(m.Type.Eq(Type))
	}
	if merchantID != "1" {
		tx = tx.Where(m.MerchantID.Eq(merchantID))
	}
	if startTime != "" && endTime != "" {
		start := carbon.Parse(startTime).StartOfDay().ToStdTime()
		end := carbon.Parse(endTime).EndOfDay().ToStdTime()
		tx = tx.Where(m.AddTime.Between(start, end))
	}
	res, count, err = tx.Order(m.AddTime.Desc()).FindByPage(Offset(page, limit))
	return
}
